#include "SensorComponent.h"
#include "GameObject.h"
#include "PhysicsComponent.h"
#include "..\EnumDefine.h"


SensorComponent::SensorComponent(FixtureID p_fixtureID, b2Vec2 p_setAsBox, b2Vec2 p_setSensorPosition, float p_angle, int p_categoryCollisionID, int p_maskCollisionFilter) : m_beginContactCallback(nullptr), m_endContactCallback(nullptr), m_fixtureID(p_fixtureID), m_setAsBox(p_setAsBox), m_setSensorPosition(p_setSensorPosition), m_angle(p_angle), m_categoryCollisionID(p_categoryCollisionID), m_maskCollisionFilter(p_maskCollisionFilter)
{
}


SensorComponent::~SensorComponent(void)
{
	/*GameObject* go = getOwner();
	if (go != nullptr)
	{
		PhysicsComponent* physics = dynamic_cast<PhysicsComponent*>(getOwner()->getComponent("PhysicsComponent"));
		if (physics != nullptr)
		{
			physics->getBody()->DestroyFixture(m_fixture);
		}
	}*/
}

void SensorComponent::init()
{
		IComponent* physicsComponent =  getOwner()->getComponent("PhysicsComponent");
		PhysicsComponent* physics = static_cast<PhysicsComponent*>(physicsComponent);

		b2FixtureDef fixtDef;
		b2PolygonShape shape;
		shape.SetAsBox(m_setAsBox.x * SCALEBOX, m_setAsBox.y * SCALEBOX, b2Vec2(m_setSensorPosition.x * SCALEF, m_setSensorPosition.y * SCALEF), m_angle);
		fixtDef.shape = &shape;
		fixtDef.isSensor = true;
		fixtDef.filter.categoryBits = m_categoryCollisionID;
		fixtDef.filter.maskBits = m_maskCollisionFilter;
		m_fixture = physics->getBody()->CreateFixture(&fixtDef);
		m_fixture->SetUserData((void*)m_fixtureID);
		
}

void SensorComponent::beginContact()
{
	if(m_beginContactCallback != nullptr)
	{
		m_beginContactCallback();
	}
}

void SensorComponent::endContact()
{
	if(m_endContactCallback != nullptr)
	{
		m_endContactCallback();
	}
}

void SensorComponent::registerBeginContactCallback(std::function<void()> p_func)
{
	m_beginContactCallback = p_func;
}

void SensorComponent::registerEndContactCallback(std::function<void()> p_func)
{
	m_endContactCallback = p_func;
}